<template>
  <div class="onekit-editor"
       :class="onekitClass"
       :style="{ onekitStyle, '--color': '#ccc' }"
       :id="onekitId"
       :placeholder="placeholder"
       :readonly="readOnly"
       @focus="_focus"
       @blur="_blur"
       @input="_input"
       :contenteditable="!readOnly"></div>
</template>

<script>
import weixin_behavior from "../../behaviors/weixin_behavior";
import onekit_behavior from "../../behaviors/onekit_behavior";
export default {
  name: "onekit-editor",
  data: () => ({ val: "" }),
  mixins: [weixin_behavior, onekit_behavior],
  props: {
    "read-only": [Boolean, String],
    placeholder: String,
  },
  methods: {
    _emitDataAndReg (type) {
      const reg = /<[^>]+>/g;
      let nodeEleVal;
      let val = this.val;
      if (reg.test(this.val)) {
        nodeEleVal = this.val;
      } else {
        nodeEleVal = `<p>${this.val}</p>`;
      }
      const data = {
        currentTarget: {
          dataset: {},
          id: this.onekitId,
          offsetLeft: 0,
          offsetTop: 0,
        },
        detail: {
          html: nodeEleVal,
          text: val,
          delta: "",
        },
        mark: {},
        mut: false,
        target: {
          dataset: {},
          id: this.onekitId,
          offsetLeft: 0,
          offsetTop: 0,
        },
        tamStamp: new Date().getTime(),
        type,
      };
      return data;
    },
    _focus () {
      const Focusdata = this._emitDataAndReg("focus");
      this.$emit("Focus", Focusdata);
    },
    _blur () {
      const blurData = this._emitDataAndReg("blur");
      this.$emit("Blur", blurData);
    },
    _input () {
      const inputData = this._emitDataAndReg("input");
      this.$emit("Input", inputData);
    },
  },
  mounted () {
    const Readydata = {
      currentTarget: {
        dataset: {},
        id: this.onekitId,
        offsetLeft: 0,
        offsetTop: 0,
      },
      detail: {},
      mark: {},
      mut: false,
      target: {
        dataset: {},
        id: this.onekitId,
        offsetLeft: 0,
        offsetTop: 0,
      },
      tamStamp: new Date().getTime(),
      type: "ready",
    };
    this.$emit("Ready", Readydata);
  },
};
</script>

<style scoped>
.onekit-editor:empty:before {
  content: attr(placeholder);
  color: var(--color);
  font-style: oblique;
}

.onekit-editor:focus:before {
  content: none;
}
</style>
